import {get_access_token} from "src/utils/token";
import {useUserStore} from "stores/user";
import {designerStore} from "src/stores/designerTool/designerTool";
const showUserStore = useUserStore()
const designerState=designerStore()
const at = get_access_token();
function isOpen(ws:any) {
  return ws.readyState === ws.OPEN
}

// let socket = null; // 定义一个 WebSocket 变量
// export function sockets() {
//   if (at) {
//     if (!socket || socket.readyState === WebSocket.CLOSED) {
//       // 如果 socket 为 null 或已经关闭，创建一个新的 WebSocket 连接
//       socket = new WebSocket(`wss://biosystest.zelixir.com/ws/?token=${at}`);
//       socket.addEventListener('open', function() {
//         console.log('连接服务器成功');
//       });
//       socket.addEventListener('close', function() {
//         console.log('连接已关闭，尝试重新连接...');
//         // 在连接关闭后，尝试重新连接
//         setTimeout(sockets, 2000); // 2秒后重新连接
//       });
//       socket.addEventListener('message', function(e) {
//         if (JSON.parse(e.data).type !== 'pong') {
//           showUserStore.notifyObservers(e.data);
//           if (JSON.parse(e.data).type == 'workflow_status_update') {
//             designerState.WORKFLOW_WEBSOCKET_DAG(e.data);
//           }
//         }
//       });
//       socket.addEventListener('error', function(error) {
//         console.log('Socket error: ' + error);
//       });
//     }
//   }
// }

export function sockets () {
  if( at ){
    let socket = new WebSocket(`wss://biosystest.zelixir.com/ws/?token=${at}`);
    //心跳包内容
    const heartBeat = {
      type: "ping",
      timestamp: new Date().getTime()
    }
    //定时发送心跳包
    setInterval(function() {
      if (isOpen(socket)) {
        socket.send(JSON.stringify(heartBeat));
      }
    }, 10000);
    socket.addEventListener('open', function(){
      console.log('连接服务器成功')
    });
    socket.onclose = function() {
      socket = new WebSocket(`wss://biosystest.zelixir.com/ws/?token=${at}`);
    }
    socket.addEventListener('message',function(e){
      if( JSON.parse(e.data).type !== 'pong' ){
        showUserStore.notifyObservers(e.data)
        if( JSON.parse(e.data).type == 'workflow_status_update' ){
          designerState.WORKFLOW_WEBSOCKET_DAG(e.data)
        }
      }
    })
    socket.onerror = function(error) {
      console.log('Socket error: ' + error)
    }
  }
}

